package com.example.droideep.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.droideep.R;
import com.example.droideep.common.activities.SimpleFragmentBase;
import com.example.droideep.common.dummydata.Cheeses;
import com.example.droideep.common.dummydata.Dummy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import droideep.library.widget.IndexBar;


public class IndexBarFragment extends SimpleFragmentBase {

    private TextView previewTV;
    private ListView listView;
    private Map<String, Integer> sections = new HashMap<String, Integer>();
    private final List<String> cheeses = Cheeses.sortList();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final int size = cheeses.size();
        for (int i = 0; i < size; i++) {
            String alphabet = cheeses.get(i).substring(0, 1);
            if (!sections.containsKey(alphabet)) {
                sections.put(alphabet, i);
            }
        }
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_index_bar;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        previewTV = (TextView) view.findViewById(R.id.previewText);

        IndexBar indexBar = (IndexBar) view.findViewById(R.id.index_bar);
        indexBar.setSections(new Dummy().getSections());
        indexBar.setIndexBarFilter(new IndexBar.IIndexBarFilter() {
            @Override
            public void filterList(float sideIndex, int position, String previewText) {
                if (sections.containsKey(previewText)) {
                    previewTV.setVisibility(View.VISIBLE);
                    previewTV.setText(previewText);
                    listView.setSelection(sections.get(previewText));
                } else {
                    previewTV.setVisibility(View.GONE);
                }
            }
        });

        listView = (ListView) view.findViewById(android.R.id.list);
        listView.setAdapter(new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                android.R.id.text1,
                cheeses));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getActivity(),
                        "Item " + position + ": " + cheeses.get(position),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}
